import { RepositoryFactory } from '../repositories';

/**
 * 基础模板种子数据
 */
export default async function seedBasicTemplates(repositories: RepositoryFactory): Promise<void> {
  const templateRepo = repositories.getTemplateRepository();
  
  console.log('🌱 开始播种基础模板数据...');

  const templates = [
    {
      name: 'BasicForm',
      category: 'form',
      framework: 'react' as const,
      description: '基础表单模板，包含常用的表单项和验证',
      template_code: `import React from 'react';
import { Form, Input, Button, Select, DatePicker, Row, Col, Card } from 'antd';

const { Option } = Select;

const BasicForm: React.FC = () => {
  const [form] = Form.useForm();

  const onFinish = (values: any) => {
    console.log('Form values:', values);
  };

  return (
    <Card title="基础表单" style={{ maxWidth: 800, margin: '0 auto' }}>
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
        autoComplete="off"
      >
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="姓名"
              name="name"
              rules={[{ required: true, message: '请输入姓名!' }]}
            >
              <Input placeholder="请输入姓名" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="性别"
              name="gender"
              rules={[{ required: true, message: '请选择性别!' }]}
            >
              <Select placeholder="请选择性别">
                <Option value="male">男</Option>
                <Option value="female">女</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="出生日期"
              name="birthDate"
              rules={[{ required: true, message: '请选择出生日期!' }]}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="手机号"
              name="phone"
              rules={[
                { required: true, message: '请输入手机号!' },
                { pattern: /^1[3-9]\\d{9}$/, message: '请输入正确的手机号!' }
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          label="地址"
          name="address"
          rules={[{ required: true, message: '请输入地址!' }]}
        >
          <Input.TextArea rows={3} placeholder="请输入详细地址" />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" size="large">
            提交
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={() => form.resetFields()}>
            重置
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default BasicForm;`,
      dependencies: ['antd', 'react'],
      popularity_score: 90,
    },
    {
      name: 'DataTable',
      category: 'table',
      framework: 'react' as const,
      description: '带分页、搜索和操作的数据表格模板',
      template_code: `import React, { useState } from 'react';
import { Table, Button, Space, Input, Card, message } from 'antd';
import { SearchOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

const { Search } = Input;

interface DataItem {
  key: string;
  name: string;
  age: number;
  address: string;
  email: string;
}

const DataTable: React.FC = () => {
  const [data, setData] = useState<DataItem[]>([
    {
      key: '1',
      name: '张三',
      age: 32,
      address: '北京市朝阳区',
      email: 'zhangsan@example.com',
    },
    // 更多示例数据...
  ]);

  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      filteredValue: searchText ? [searchText] : null,
      onFilter: (value: string, record: DataItem) =>
        record.name.toLowerCase().includes(value.toLowerCase()),
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
      sorter: (a: DataItem, b: DataItem) => a.age - b.age,
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: DataItem) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.key)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleEdit = (record: DataItem) => {
    message.info(\`编辑用户: \${record.name}\`);
  };

  const handleDelete = (key: string) => {
    setData(data.filter(item => item.key !== key));
    message.success('删除成功');
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  return (
    <Card title="数据表格" style={{ margin: '20px' }}>
      <div style={{ marginBottom: 16 }}>
        <Search
          placeholder="搜索姓名"
          allowClear
          enterButton={<SearchOutlined />}
          size="middle"
          onSearch={handleSearch}
          style={{ width: 300 }}
        />
      </div>
      
      <Table
        columns={columns}
        dataSource={data}
        loading={loading}
        pagination={{
          total: data.length,
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            \`\${range[0]}-\${range[1]} 共 \${total} 条\`,
        }}
      />
    </Card>
  );
};

export default DataTable;`,
      dependencies: ['antd', 'react', '@ant-design/icons'],
      popularity_score: 85,
    },
    {
      name: 'DashboardLayout',
      category: 'layout',
      framework: 'react' as const,
      description: '后台管理系统布局模板，包含侧边栏和顶部导航',
      template_code: `import React, { useState } from 'react';
import {
  Layout,
  Menu,
  Breadcrumb,
  theme,
  Button,
  Avatar,
  Dropdown,
  Space,
} from 'antd';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
  DashboardOutlined,
  TableOutlined,
  FormOutlined,
  SettingOutlined,
  LogoutOutlined,
} from '@ant-design/icons';

const { Header, Sider, Content } = Layout;

const DashboardLayout: React.FC<{ children?: React.ReactNode }> = ({
  children,
}) => {
  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer },
  } = theme.useToken();

  const menuItems = [
    {
      key: '1',
      icon: <DashboardOutlined />,
      label: '仪表盘',
    },
    {
      key: '2',
      icon: <TableOutlined />,
      label: '数据表格',
    },
    {
      key: '3',
      icon: <FormOutlined />,
      label: '表单页面',
    },
    {
      key: '4',
      icon: <SettingOutlined />,
      label: '系统设置',
    },
  ];

  const userMenuItems = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人中心',
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '个人设置',
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      danger: true,
    },
  ];

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div
          style={{
            height: 32,
            margin: 16,
            background: 'rgba(255, 255, 255, 0.2)',
            borderRadius: 6,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'white',
            fontWeight: 'bold',
          }}
        >
          {collapsed ? 'LOGO' : 'My Dashboard'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={['1']}
          items={menuItems}
        />
      </Sider>
      <Layout>
        <Header
          style={{
            padding: 0,
            background: colorBgContainer,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: '16px',
              width: 64,
              height: 64,
            }}
          />
          
          <Space style={{ marginRight: 24 }}>
            <Dropdown
              menu={{
                items: userMenuItems,
                onClick: ({ key }) => {
                  if (key === 'logout') {
                    console.log('用户登出');
                  }
                },
              }}
              placement="bottomRight"
            >
              <Space style={{ cursor: 'pointer' }}>
                <Avatar size="small" icon={<UserOutlined />} />
                <span>用户名</span>
              </Space>
            </Dropdown>
          </Space>
        </Header>
        
        <Content style={{ margin: '0 16px' }}>
          <Breadcrumb
            style={{ margin: '16px 0' }}
            items={[
              { title: '首页' },
              { title: '仪表盘' },
            ]}
          />
          <div
            style={{
              padding: 24,
              minHeight: 360,
              background: colorBgContainer,
              borderRadius: 6,
            }}
          >
            {children || '页面内容区域'}
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default DashboardLayout;`,
      dependencies: ['antd', 'react', '@ant-design/icons'],
      popularity_score: 95,
    },
    {
      name: 'LoginForm',
      category: 'auth',
      framework: 'react' as const,
      description: '登录表单模板，包含用户名密码和验证码',
      template_code: `import React from 'react';
import { Form, Input, Button, Card, Checkbox, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';

interface LoginFormValues {
  username: string;
  password: string;
  remember: boolean;
}

const LoginForm: React.FC = () => {
  const [form] = Form.useForm();

  const onFinish = async (values: LoginFormValues) => {
    try {
      console.log('登录信息:', values);
      message.success('登录成功！');
      // 这里添加实际的登录逻辑
    } catch (error) {
      message.error('登录失败，请检查用户名和密码');
    }
  };

  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        minHeight: '100vh',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      }}
    >
      <Card
        title="用户登录"
        style={{
          width: 400,
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
        }}
        headStyle={{
          textAlign: 'center',
          fontSize: '24px',
          fontWeight: 'bold',
        }}
      >
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名!' },
              { min: 3, message: '用户名至少3个字符!' },
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码!' },
              { min: 6, message: '密码至少6个字符!' },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
            />
          </Form.Item>

          <Form.Item>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住我</Checkbox>
              </Form.Item>
              <a href="#" style={{ float: 'right' }}>
                忘记密码？
              </a>
            </div>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              style={{ width: '100%' }}
            >
              登录
            </Button>
          </Form.Item>

          <div style={{ textAlign: 'center' }}>
            还没有账号？ <a href="#">立即注册</a>
          </div>
        </Form>
      </Card>
    </div>
  );
};

export default LoginForm;`,
      dependencies: ['antd', 'react', '@ant-design/icons'],
      popularity_score: 88,
    },
  ];

  console.log(`📦 准备播种 ${templates.length} 个模板...`);

  for (let i = 0; i < templates.length; i++) {
    const template = templates[i];
    if (!template) {
      console.warn(`⚠️  Skipping undefined template at index ${i}`);
      continue;
    }
    try {
      console.log(`📝 创建模板: ${template.name} (${i + 1}/${templates.length})`);
      
      await templateRepo.create(template);
      console.log(`✅ 模板 ${template.name} 创建成功`);
    } catch (error) {
      console.error(`❌ 模板 ${template.name} 创建失败:`, error);
      throw error;
    }
  }

  console.log('🎉 基础模板数据播种完成！');
}